package com.xy6.dpdemo.book.chapter09.prototype;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.math.BigDecimal;

/**
 * 简历bean
 * <p>实现Cloneable接口，以重写clone方法
 * <p>实现Serializable接口，以通过序列化技术实现深度复制
 * 
 * @author zhang
 * @since 2017-06-18
 */
public class Resume implements Cloneable, Serializable {

	private static final long serialVersionUID = -4273355898900512898L;

	private String name;
	
	private String sex;
	
	/**
	 * 复制时，与string表现相同，对第2个变量值修改，不影响第1个变量值，为什么？
	 * 因为对第2个变量赋值时，new一个对象，可看BigDecimal.ONE实现。
	 */
	private BigDecimal salary;
	
	private WorkExp work;
	
	public Resume(){
	}
	
	public Resume(String name, String sex){
		this.name = name;
		this.sex = sex;
		work = new WorkExp();
	}
	
	public void setWorkExp(String timeArea, String company){
		work.setTimeArea(timeArea);
		work.setCompany(company);
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getSex() {
		return sex;
	}

	public void setSex(String sex) {
		this.sex = sex;
	}

	public BigDecimal getSalary() {
		return salary;
	}

	public void setSalary(BigDecimal salary) {
		this.salary = salary;
	}

	public WorkExp getWork() {
		return work;
	}

	public void setWork(WorkExp work) {
		this.work = work;
	}

	@Override
	public String toString() {
		return "Resume [name=" + name + ", sex=" + sex + ", salary=" + salary + ", work=" + work + "]";
	}

	public void display(){
		System.out.println(this.toString());
	}
	
	public Resume clone(){
		try {
			return (Resume)super.clone();
		} catch (CloneNotSupportedException e) {
			e.printStackTrace();
			throw new InternalError();
		}
	}
	
	/**
	 * 深度复制
	 * 
	 * @return
	 */
	public Resume deepClone(){
		try {
			WorkExp work = new WorkExp(this.getWork().getTimeArea(), this.getWork().getCompany());
			Resume resume = (Resume)super.clone();
			resume.setWork(work);
			return resume;
		} catch (CloneNotSupportedException e) {
			e.printStackTrace();
			throw new InternalError();
		}
	}
	
	/**
	 * 深度复制
	 * <p>利用序列号来做深度复制，将对象以流的形式写入一个字节数组，再写出
	 * 
	 * @return
	 */
	public Resume deepClone2(){
		try {
			ByteArrayOutputStream bo = new ByteArrayOutputStream();
			ObjectOutputStream oo = new ObjectOutputStream(bo);
			oo.writeObject(this);
			
			ByteArrayInputStream bi = new ByteArrayInputStream(bo.toByteArray());
			ObjectInputStream oi = new ObjectInputStream(bi);
			return (Resume) oi.readObject();
		} catch (IOException e) {
			e.printStackTrace();
			throw new InternalError();
		} catch(ClassNotFoundException e){
			e.printStackTrace();
			throw new InternalError();
		}
	}
	
}
